import Loading from '@c/loading'
import styles from './index.module.scss'
import { useEffect, useState, useRef } from 'react'
import cm from 'classnames'
import { getVodCollectList, getLiveCollectList } from '@/api/history-collect'
import throttle from 'lodash-es/throttle'
import { isElementInViewport } from '@/utils/utils'
import Collect from './collect'
const Index = () => {
  const [pageNo, setPageNo] = useState(0)
  const [pageVodNo, setPageVodNo] = useState(3)
  const [pageLiveNo, setPageLiveNo] = useState(3)
  const [isLoading, setLoading] = useState(false)
  const ref = useRef(null)
  const [init, setInit] = useState(false)
  const [isVodEnd, setIsVodEnd] = useState(false)
  const [isLiveEnd, setIsLiveEnd] = useState(false)
  const [playType, setPlayType] = useState('vod')
  const [liveData, setLiveData] = useState([])
  const [vodData, setVodData] = useState([])

  // 数据初始化&切换tab更新
  const initData = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      return
    }
    const params = { pageNo: 1, pageSize: 21 }
    const resArr = (await Promise.all([getVodCollectList(params, token), getLiveCollectList(params, token)])).map(
      item => {
        if (item.code) {
          return []
        }
        return item?.data?.records || item?.data?.list || []
      }
    )
    setInit(true)
    setVodData(resArr[0])
    setLiveData(resArr[1])
    setIsVodEnd(!resArr[0].length)
    setIsLiveEnd(!resArr[1].length)
  }

  // 下滑加载更多函数
  const slideLoadMore = async playType => {
    setLoading(true)
    const token = localStorage.getItem('token')
    if (!token) return

    if (playType === 'vod') {
      if (!vodData.length) return
      const res = await getVodCollectList({ pageNo: pageVodNo, pageSize: 7 }, token)
      const list = res?.data?.list || res?.data?.records || []
      setVodData([...vodData, ...list].flat(1))
      setIsVodEnd(!list.length)
    } else {
      if (!liveData.length) return
      const res = await getLiveCollectList({ pageNo: pageLiveNo, pageSize: 7 }, token)
      const list = res?.data?.list || res?.data?.records || []
      setLiveData([...liveData, ...list].flat(1))
      setIsLiveEnd(!list.length)
    }
    setLoading(false)
  }
  // page变化，加载数据
  useEffect(() => {
    if (!init) return
    if (playType === 'live') {
      setPageLiveNo(pageLiveNo + 1)
    } else {
      setPageVodNo(pageVodNo + 1)
    }
  }, [pageNo])
  useEffect(() => {
    if (!init || pageVodNo <= 3 || isVodEnd) {
      setLoading(false)
      return
    }
    slideLoadMore('vod')
  }, [pageVodNo])
  useEffect(() => {
    if (!init || pageLiveNo <= 3 || isLiveEnd) {
      setLoading(false)
      return
    }
    slideLoadMore('live')
  }, [pageLiveNo])

  const handleScroll = () => {
    if (isElementInViewport(ref.current)) {
      setPageNo(page => page + 1)
    }
  }

  // tab切换，数据状态修改
  useEffect(() => {
    initData()
  }, [])

  useEffect(() => {
    // 触底加载更多
    const scrollListen = throttle(() => handleScroll(playType), 500)
    window.addEventListener('scroll', scrollListen)
    return () => {
      window.removeEventListener('scroll', scrollListen)
    }
  }, [])

  // 切换直播
  const toLive = () => {
    setPlayType('live')
  }
  // 切换点播
  const toVod = () => {
    setPlayType('vod')
  }
  return (
    <div className={styles.items}>
      <div className={styles.itemsTab} style={{ marginBottom: 32 }}>
        <div className={cm(styles.itemText, 'hideWhenPc')}>我的收藏</div>
        <div>
          <span
            onClick={toVod}
            className={cm(styles.itemsTabItem, playType === 'vod' ? styles.itemsTabItemActive : '')}
          >
            点播
          </span>
          <span
            onClick={toLive}
            className={cm(styles.itemsTabItem, playType === 'live' ? styles.itemsTabItemActive : '')}
          >
            直播
          </span>
        </div>
      </div>
      <Collect playType={playType} liveData={liveData} vodData={vodData} init={init} />
      <div className={styles.loading}>
        <Loading isLoading={isLoading} ref={ref} />
      </div>
    </div>
  )
}
export default Index
